<template>
  <div class="component-upload-image">
    <!--通用上传文件和图片-->
    <div style="display: flex">
      <el-upload
        :multiple="multiple"
        :action="uploadFileUrl"
        list-type="picture-card"
        :on-success="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        ref="uploadRef"
        :before-remove="handleDelete"
        :show-file-list="true"
        :headers="headers"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
        :class="{ hide: fileList.length >= limit }">
        <!-- 上传按钮 -->
        <!-- <el-button type="primary">选取文件</el-button> -->
        <div style="display: flex; justify-content: center; flex-direction: column; align-items: center">
          <el-icon class="avatar-uploader-icon">
            <svg-icon :icon-class="icon"></svg-icon>
          </el-icon>
          <span style="font-size: 13px; color: #999999">选择</span>
        </div>
        <template #file="{ file }">
          <div>
            <img v-if="checkSuffix(file.url)" class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <div v-else style="padding: 12px">
              <el-image :src="types[getFileSuffix(file.url)]" fit="fill" />
            </div>
            <span class="el-upload-list__item-actions">
              <span v-if="checkSuffix(file.url)" class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <el-icon><zoom-in /></el-icon>
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file.url)">
                <el-icon>
                  <Download />
                </el-icon>
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDelete(file)">
                <el-icon>
                  <Delete />
                </el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>
    </div>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过<span style="color: #f56c6c">{{ fileSize }}MB</span>
      </template>
      <template v-if="fileType">
        格式为<span style="color: #f56c6c">{{ fileType.join("/") }}</span>
      </template>
      的文件
    </div>
    <el-image-viewer v-if="dialogVisible" :url-list="[dialogImageUrl]" @close="dialogVisible = false" teleported />
  </div>
</template>

<script setup lang="ts">
import { listByIds, delOss } from "@/api/system/oss";
import { OssVO } from "@/api/system/oss/types";
import { propTypes } from "@/utils/propTypes";
import { globalHeaders } from "@/utils/request";

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: propTypes.number.def(5),
  // 大小限制(MB)
  fileSize: propTypes.number.def(5),
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: propTypes.array.def(["png", "jpg", "jpeg", "gif", "txt", "pdf", "xls", "xlsx", "docx", "doc", "zip", "rar", "mp3", "mp4"]),
  // 是否显示提示
  isShowTip: propTypes.bool.def(true),
  // 是否允许多选
  multiple: propTypes.bool.def(true),
  // 图标
  icon: propTypes.string.def("plus")
});

const dialogVisible = ref(false);
const dialogImageUrl = ref("");

// 判断可预览的类型
const suffix = ["png", "jpg", "jpeg", "gif"];

const types = ref({
  txt: new URL("../../assets/types/txt.png", import.meta.url).href,
  pdf: new URL("../../assets/types/pdf.png", import.meta.url).href,
  doc: new URL("../../assets/types/doc.png", import.meta.url).href,
  docx: new URL("../../assets/types/docx.png", import.meta.url).href,
  xls: new URL("../../assets/types/xls.png", import.meta.url).href,
  xlsx: new URL("../../assets/types/xlsx.png", import.meta.url).href,
  rar: new URL("../../assets/types/rar.png", import.meta.url).href,
  zip: new URL("../../assets/types/zip.png", import.meta.url).href,
  mp3: new URL("../../assets/types/mp4.png", import.meta.url).href,
  mp4: new URL("../../assets/types/mp4.png", import.meta.url).href,
  other: new URL("../../assets/types/nullImg.png", import.meta.url).href
});
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(["update:modelValue"]);
const number = ref(0);
const uploadList = ref<any[]>([]);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + "/resource/oss/upload"); // 上传文件服务器地址
const headers = ref(globalHeaders());

const fileList = ref<any[]>([]);
const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));

const uploadRef = ref<ElUploadInstance>();

watch(
  () => props.modelValue,
  async val => {
    if (val) {
      // 首先将值转为数组
      let list: OssVO[] = [];
      if (Array.isArray(val)) {
        list = val as OssVO[];
      } else {
        const res = await listByIds(val as string);
        list = res.data;
      }
      // 然后将数组转为对象数组
      fileList.value = list.map((item: any) => {
        // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
        if (typeof item === "string") {
          item = { name: item, url: item };
        } else {
          // 此处name使用ossId 防止删除出现重名
          item = { name: item.originalName, url: item.url, ossId: item.ossId };
        }
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);
/**
 * 判断是否为图片
 */
function checkSuffix(name) {
  let suffixName = name.split(".").pop().toLowerCase();
  if (suffix.includes(suffixName)) {
    return true;
  }
  return false;
}
const getFileSuffix = url => {
  try {
    let suffixName = url.split(".").pop().toLowerCase();
    return suffixName;
  } catch (e) {
    return "other";
  }
};

// 预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

// 上传前loading加载
function handleBeforeUpload(file) {
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some((type: any) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }
  if (!isImg) {
    proxy?.$modal.msgError(`文件格式不正确, 请上传 ${props.fileType.join("/")} 格式的文件!`);
    return false;
  }
  if (props?.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy?.$modal.loading("正在上传，请稍候…");
  number.value++;
}

// 文件个数超出
const handleExceed = () => {
  proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
};

// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError("上传文件失败");
};

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
  if (res.code === 200) {
    uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgError(res.msg);
    uploadRef.value?.handleRemove(file);
    uploadedSuccessfully();
  }
};

function handleDownload(url) {
  window.open(url, "_blank");
}
// 删除文件
const handleDelete = file => {
  // let ossId = fileList.value[index].ossId;
  const findex = fileList.value.map(f => f.name).indexOf(file.name);
  if (findex > -1 && uploadList.value.length === number.value) {
    let ossId = fileList.value[findex].ossId;
    delOss(ossId);
    fileList.value.splice(findex, 1);
    emit("update:modelValue", listToString(fileList.value));
  }
};

// 上传结束处理
const uploadedSuccessfully = () => {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit("update:modelValue", listToString(fileList.value));
    proxy?.$modal.closeLoading();
  }
};

// 对象转成指定字符串分隔
const listToString = (list: any[], separator?: string) => {
  let strs = "";
  separator = separator || ",";
  list.forEach(item => {
    if (item.ossId) {
      strs += item.ossId + separator;
    }
  });
  return strs != "" ? strs.substring(0, strs.length - 1) : "";
};
</script>

<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
  display: none;
}
</style>
